package com.vegsan.taskreminder;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
//import android.view.View.OnFocusChangeListener;
//import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
//import android.widget.TextView;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class ReminderEditActivity extends Activity {

private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private EditText mTitleText;
private EditText mBodyTest;

private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TEME_FORMAT = "kk:mm";
private Calendar mCalendar;
private ReminderDbAdapter mDbHelper;
private Long mRowId;

static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";



@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	mDbHelper = new ReminderDbAdapter(this);
	setContentView(R.layout.reminder_edit);
	
	mCalendar = Calendar.getInstance();
	mTitleText = (EditText)findViewById(R.id.title);
	mBodyTest = (EditText)findViewById(R.id.body);
	
	mDateButton = (Button)findViewById(R.id.reminder_date);
	mTimeButton = (Button)findViewById(R.id.time);
	mConfirmButton = (Button)findViewById(R.id.confirm);

	//mRowId1 = savedInstanceState != null?savedInstanceState.getLong(ReminderDbAdapter.KEY_ROWID):null;
	//Long l1 = true?null:1;
	if (savedInstanceState != null) {
		mRowId = savedInstanceState.getLong(ReminderDbAdapter.KEY_ROWID);
	} else {
		mRowId = null;
		
	}
	
	registerButtonListenersAndSetDefaultText();
	
}


private void setRowIdFromIdent(){
	if (mRowId == null) {
		Bundle extras = getIntent().getExtras();
		
		
		if (extras != null){
			mRowId = extras.getLong(ReminderDbAdapter.KEY_ROWID);
		} else {
			mRowId = null;
		}
		
		//mRowId = extras != null ? extras.getLong(ReminderDbAdapter.KEY_ROWID):null;
	}
}



@Override
	protected void onPause() {
		super.onPause();
		mDbHelper.close();
	}


@Override
	protected void onResume() {
		super.onResume();
		mDbHelper.open();
		setRowIdFromIdent();
		populateFields();
	}

 
private void populateFields() {
	if (mRowId != null){
		Cursor reminder = mDbHelper.fetchReminder(mRowId);
		startManagingCursor(reminder);
		mTitleText.setText(reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_TITLE)));
		mBodyTest.setText(reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_BODY)));
		SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
		Date date = null;
		try {
			String dateString = reminder.getString(reminder.getColumnIndexOrThrow(ReminderDbAdapter.KEY_DATE_TIME));
			date = dateTimeFormat.parse(dateString);
			mCalendar.setTime(date);
			
		} catch (ParseException e) {
			Log.e("ReminderEditActivity", e.getMessage(), e);
		}
		
		// Cancel expired notification
		Calendar currentTime = Calendar.getInstance();
		currentTime.setTimeInMillis(System.currentTimeMillis());
		
		if (mCalendar.compareTo(currentTime)<1) {
			NotificationManager notifManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
			notifManager.cancel((int)(long)mRowId);
		}
				
	} else {
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		String defaultTitleKey = getString(R.string.pref_task_title_key);
		String defaultTimeKey  = getString(R.string.pref_default_time_from_now_key);
		String defaultTitle    = pref.getString(defaultTitleKey, "");
		String defaultTime    = pref.getString(defaultTitle, "");
		if ("".equals(defaultTitle)== false){
			mTitleText.setText(defaultTitle);
		}		
		if ("".equals(defaultTime)==false){
			mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
		}
	}
	updateDateButtonText();
	updateTimeButtonText();
}

@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong(ReminderDbAdapter.KEY_ROWID, mRowId);
		
	}



private void registreTitleFocusChange() {
	
	mTitleText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			// TODO Auto-generated method stub
			//if (mTitleText.getText().toString().equals(""))  {
				Toast.makeText(ReminderEditActivity.this, "Please fill the title", Toast.LENGTH_SHORT).show();
			//}
		}
	});
	
}

private void registerConfirmationDialog() {
	
mConfirmButton.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(ReminderEditActivity.this);
			builder.setMessage("Do you want to save it?")
				.setTitle("Save confirmation")
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//						
					}
				})
			
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						
					}
				});

			
		builder.create().show();
		}
	});

}

private void registerButtonListenersAndSetDefaultText() {
	// TODO Auto-generated method stub
	mDateButton.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(DATE_PICKER_DIALOG);
		
		}
	});
	updateDateButtonText();
	
	mTimeButton.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showDialog(TIME_PICKER_DIALOG);
			
		}
	});
	
	
	updateTimeButtonText();
	
	
	
	
	mConfirmButton.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			saveState();
			setResult(RESULT_OK);
			finish();

			
			//Toast.makeText(ReminderEditActivity.this, getString(R.string.saved_text), Toast.LENGTH_SHORT);
			
		}
	
	});
		
}

private void saveState() {
String title = mTitleText.getText().toString();
	String body = mBodyTest.getText().toString();
	SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
	String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
	if (mRowId == null) {
		long id = mDbHelper.createReminder(title,body,reminderDateTime);
		if (id > 0){ 
			mRowId = id;
			}
		}
		else {
			mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
	}
	new ReminderManager(this).setReminder(mRowId, mCalendar);
}
	


private void updateTimeButtonText() {
	SimpleDateFormat timeFormat = new SimpleDateFormat(TEME_FORMAT);
	String timeForButton = timeFormat.format(mCalendar.getTime());
	mTimeButton.setText(timeForButton); 
	
}

private void updateDateButtonText() {
	// TODO Auto-generated method stub
	SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
	String dateForButton = dateFormat.format(mCalendar.getTime());
	mDateButton.setText(dateForButton);
}

@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// ������ ����� ������������� ������
			
	}

@Override
	protected Dialog onCreateDialog(int id) {
		switch (id){
			case DATE_PICKER_DIALOG:
				return showDatePicker();
			case TIME_PICKER_DIALOG:
				return showTimePicker();
		}
		
		return super.onCreateDialog(id);
	}

private TimePickerDialog showTimePicker() {
	TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
			mCalendar.set(Calendar.MINUTE, minute);
			updateTimeButtonText();
		}
	}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE),true);
	
	return timePicker;
}

private DatePickerDialog showDatePicker() {
		
	DatePickerDialog datePicker = new DatePickerDialog(ReminderEditActivity.this, new DatePickerDialog.OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			mCalendar.set(Calendar.YEAR, year);
			mCalendar.set(Calendar.MONTH, monthOfYear);
			mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			updateDateButtonText();
		}
	}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
	
	
	return datePicker;
}

}
